#ifndef ASYNC_HANDLER_H
#define ASYNC_HANDLER_H

#include <stdint.h>
#include <pthread.h>
#include "common_list.h"

#define LOOP_NAME_LEN 16
#define MAX_LOOPER_CNT 30U


typedef struct AsyncMessage AsyncMessage;
typedef struct AsyncHandler AsyncHandler;
typedef struct AsyncLooper AsyncLooper;



typedef struct AsyncLooperContext {
    ListNode msgHead;
    char name[LOOP_NAME_LEN];
    volatile int stop;
    pthread_mutex_t lock;
    pthread_cond_t cond;
    pthread_t thread;
} AsyncLooperContext;

struct AsyncLooper {
    AsyncLooperContext *context;
    void (*PostMessage)(const AsyncLooper *looper, AsyncMessage *msg);
};

struct AsyncMessage {
    int32_t what;
    void *obj;
    AsyncHandler *handler;
    void (*FreeMessage)(AsyncMessage *msg);
    void (*HandleMessage)(AsyncMessage *msg);
};


struct AsyncHandler {
    const char *name;
    AsyncLooper *looper;
};



AsyncLooper *CreateAsyncLooper(const char *name);
void DestroyAsyncLooper(AsyncLooper *looper);

AsyncMessage *MallocAsyncMessage(void);
void FreeAsyncMessage(AsyncMessage *msg);

#endif // ASYNC_HANDLER_H
